from io import BytesIO

import requests

import plugins
from bridge.context import ContextType
from bridge.reply import Reply, ReplyType
from common.log import logger
from plugins import *


@plugins.register(
    name="HeiSi",
    desire_priority=101,
    hidden=False,
    desc="小姐姐",
    version="0.1",
    author="刘小龙",
)
class HeiSiPlugin(Plugin):
    def __init__(self):
        super().__init__()
        try:
            self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
            logger.info("[HeiSiPlugin] inited.")
        except Exception as e:
            logger.warn("[HeiSiPlugin] init failed, ignore.")
            raise e

    def on_handle_context(self, e_context: EventContext):
        if e_context["context"].type != ContextType.TEXT:
            return

        content = e_context["context"].content.strip()
        
        if content.startswith("小姐姐"):
            message = content.replace("小姐姐", "").strip()
            video_url = self.get_video_url(message)
            if video_url:
                reply = Reply(ReplyType.VIDEO_URL, video_url)
                e_context["reply"] = reply
                e_context.action = EventAction.BREAK_PASS
            else:
                reply = Reply(ReplyType.TEXT, "无法生成小姐姐视频，请稍后再试。")
                e_context["reply"] = reply

    def get_help_text(self, **kwargs):
        help_text = "输入【小姐姐】 来生成小姐姐视频。"
        return help_text

    def get_video_url(self, message):
        api_url = "http://api.yujn.cn/api/sbkl.php?type=video"
        try:
            response = requests.get(api_url, allow_redirects=False)
            if response.status_code == 302:
                location = response.headers.get('Location')
                logger.info(f"Location: {location}")
                return location
            else:
                logger.error(f"Request failed with status code: {response.status_code}")
                return None
        except requests.exceptions.RequestException as e:
            logger.error(f"Request failed: {e}")
            return None
        except ValueError:
            logger.error("Failed to parse JSON response")
            return None

# 示例调用
if __name__ == "__main__":
    plugin = HeiSiPlugin()
    print(plugin.get_video_url("小姐姐"))
